package com.zretc.util;

import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class UniqueIdentifierUtil {
	
	/**
	 * 唯一标识id
	 * @return
	 */
	public static String uniqueId() {
		LocalDateTime now = LocalDateTime.now();//时间戳
		DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
		String formatDate = ofPattern.format(now);	
		int random = (int) (Math.random()*1000+1);//随机数
		StringBuffer id = new StringBuffer();
		id.append(formatDate).append(random);//编号
		return id.toString();
	}
	/**
	 * 唯一标识图片名称
	 * @param file
	 * @return fileName
	 */
	public static String uniquePictureName(MultipartFile file) {
		//为空则返回空
		if (file.getSize() == 0) {
			return null;
		}
		//不为空则返回一个随机新图片名
		else {
			// 1获取文件名
			String fileName = file.getOriginalFilename();// 1.jpg
			// 可以自定义文件名+文件后缀名
			// 1.1 获取文件后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
			// 1.2 时间戳自定义文件名
			LocalDateTime now = LocalDateTime.now();//时间戳
			DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
			String formatDate = ofPattern.format(now);
			int random = (int) (Math.random() * 1000 + 1);//随机数
			StringBuffer newFileName = new StringBuffer();
			newFileName.append(formatDate).append(random).append(fileSuffix);//完整图片名
			return newFileName.toString();
		}
	}
	/**
	 * 唯一标识图片存储路径
	 * @param fileName
	 * @return filePath
	 */
	public static String uniquePicturePath(String fileName) {
		if (fileName!=null) {
			File file = new File("D:\\fileupload\\images");//图片固定路径
			return file.getPath() + File.separator + fileName;
		}else {
			return null;
		}
	}
}
